﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConnectSQLServer.Common;
using Crownwood.Magic.Controls;
using ConnectSQLServer.Controls;


namespace ConnectSQLServer.Manager
{
    public class TableManager
    {
        public void Saved()
        {
            TabPage tabpage = GlobalVariable.TCManager.GetTabPageSelected();
            if (tabpage.Name == "TableDesign")
            {
                if (tabpage.Tag.ToString() == "Unsave")
                {
                    tabpage.Title = tabpage.Title.Substring(0, tabpage.Title.Length - 2);
                    tabpage.Tag = "Save";
                }
            }
        }
        public void RowChanged()
        {
            TabPage tabpage = GlobalVariable.TCManager.GetTabPageSelected();
            if (tabpage.Name == "TableDesign")
            {
                if (tabpage.Tag.ToString() == "Save")
                {
                    tabpage.Title = tabpage.Title + "*";
                    tabpage.Tag = "Unsave";
                }
            }
        }
        public void ShowTableDesign(InfoDatabase info)
        {
            TabPage tp = new TabPage(info.DatabaseName + "_" + info.TableName);
            tp.Name = "TableDesign";
            tp.Tag = "Save";
            MyTable newTableDeisg = new MyTable(1, info);
            FillTableDesignDGV(newTableDeisg.dgv, info);
            newTableDeisg.Location = new System.Drawing.Point(0, 0);
            newTableDeisg.Size = new System.Drawing.Size(GlobalVariable.widthPanel2, GlobalVariable.heightPanel2 - GlobalVariable.padding);
            tp.Controls.Add(newTableDeisg);
            MyDataTable dt = new MyDataTable();
            dt.Location = new System.Drawing.Point(0, GlobalVariable.heightPanel2 / 2);
            dt.Size = new System.Drawing.Size(0, 0);
            tp.Controls.Add(dt);
            GlobalVariable.TCManager.AddTabPage(tp);
            GlobalVariable.iNewQuery++;
        }

        private void FillTableDesignDGV(System.Windows.Forms.DataGridView dgv, InfoDatabase info)
        {
            foreach (Microsoft.SqlServer.Management.Smo.Column col in info.SERVER.Databases.ItemById(info.DatabaseID).Tables.ItemById(info.TableID).Columns)
            {
                if (col.Name != null)
                {
                    int index = dgv.Rows.Add();
                    dgv.Rows[index].Cells[0].Value = col.Name;
                    dgv.Rows[index].Cells[1].Value = col.DataType.Name + "(" + col.DataType.MaximumLength.ToString() + ")";
                    dgv.Rows[index].Cells[2].Value = col.Nullable;
                }
            }
        }

    }
}
